﻿using System;
using System.Data;
using System.Data.Common;

//自定义命名空间
using DreamCube.Framework.DataAccess.Basic;
using DreamCube.Framework.DataAccess.Sqlserver;
using DreamCube.Foundation.Basic.Objects.Log;

namespace PicServer.DAL
{
    public class FileTable
    {
        /// <summary>
        /// 获取文件的索引数据
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Model.FileIndexData GetFileRecord(String tableName, Int32 code)
        {
            String sql = String.Format("select fileName,fileStartIndex,fileDataLength,fileDes,insertTime from {0} where id={1}",
                                tableName, code);
            Database db = DbManager.GetDBByName();
            DbCommand command = db.GetSqlStringCommand(sql);
            Model.FileIndexData file = null;
            using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
            {
                if (reader.Read())
                {
                    file = new Model.FileIndexData()
                    {
                        FileName = reader.GetString(0),
                        FileStartIndex = (Int64)reader.GetDouble(1),
                        FileDataLength = reader.GetInt32(2),
                        FileDes = reader.GetString(3),
                        DateTime = reader.GetDateTime(4)
                    };
                }
            }
            return file;
        }

        /// <summary>
        /// 插入记录到数据库中
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="fileName"></param>
        /// <param name="fileDes"></param>
        /// <param name="streamStartIndex"></param>
        /// <param name="dataLength"></param>
        public static Int32 InsertIntoDb(String tableName, String fileName, String fileDes, long streamStartIndex, Int32 dataLength)
        {
            String sql = String.Format("insert into {0}(fileName,fileStartIndex,fileDataLength,fileDes) " +
                            "values(@fileName,@fileStartIndex,@fileDataLength,@fileDes) SELECT @@IDENTITY;", tableName);
            Database db = DbManager.GetDBByName();
            DbCommand command = db.GetSqlStringCommand(sql);
            db.AddInParameter(command, "@fileName", System.Data.DbType.String, fileName);
            db.AddInParameter(command, "@fileStartIndex", System.Data.DbType.Int64, streamStartIndex);
            db.AddInParameter(command, "@fileDataLength", System.Data.DbType.Int32, dataLength);
            db.AddInParameter(command, "@fileDes", System.Data.DbType.String, fileDes);
            return Convert.ToInt32(db.ExecuteScalar(command));
        }
    }
}
